﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController2D : MonoBehaviour
{
    public Transform followTarget;
    public float speed = 1;
    public Vector2 cameraoffset = Vector2.zero;
    public Collider2D mapRange;
    float halfHeight, halfWeight;
    float mapleft, mapright, maptop, mapbottom;
    Camera mainCam;
    private void Start()
    {
        mapRange.isTrigger = true;
        mapleft = mapRange.bounds.min.x;
        mapright = mapRange.bounds.max.x;
        maptop = mapRange.bounds.max.y; 
        mapbottom = mapRange.bounds.min.y;
        mainCam = GetComponent<Camera>();
        halfHeight = mainCam.orthographicSize;
        halfWeight = mainCam.orthographicSize * mainCam.aspect;
    }
    public void SetTarget(Transform tr)
    {
        followTarget = tr;
    }
    bool hasFind = false;
    private void LateUpdate()
    {
        if (followTarget==null)
        {
            if (!hasFind)
            {
                Invoke("FindTarget", 1);
                hasFind = true;
            }

            return;
        }
        Vector3 targetPos = new Vector3(followTarget.transform.position.x+cameraoffset.x, followTarget.transform.position.y+cameraoffset.y, transform.position.z);
        if (targetPos.x<mapleft+halfWeight)
        {
            targetPos.x = mapleft + halfWeight;
        }
        if (targetPos.x>mapright-halfWeight)
        {
            targetPos.x = mapright - halfWeight;
        }
        if (targetPos.y>maptop-halfHeight)
        {
            targetPos.y = maptop - halfHeight;
        }
        if (targetPos.y<mapbottom+halfHeight)
        {
            targetPos.y = mapbottom + halfHeight;
        }
        transform.position = Vector3.Lerp(transform.position, targetPos, Time.deltaTime*speed);
    }
    public void FindTarget()
    {
        GameObject go= GameObject.FindGameObjectWithTag("Player");
        if(go)
            followTarget = go.transform;
    }
    public void CameraShake()
    {
        mainCam.DOShakePosition(0.1f, 0.05f);
        mainCam.DOShakeRotation(0.3f, 0.05f);
    }
}
